//
//  RCTicketFlyOrderViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-11-30.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCTicketFlyOrderViewController.h"
#import "RCTicketOrderCells.h"
#import "RCTicketFlyOrderCell.h"
#import "CommonDefines.h"
#import "RCTranlistDataModel.h"
#import "RCTrainOrderDetailInfoDataModel.h"
#import "NSArray+EX.h"
#import "IManager+ModuleTicketOrderInfo.h"
#import "MBProgressHUD.h"
#import "FrameworkRelativeDefines.h"
#import "AppDelegate.h"
#import "CommonDefines.h"
#import "UIColor-Expanded.h"
#import "NSString+NSString_Ex_.h"
#import "RCTicketAddUserViewController.h"
#import "GloableEngineService.h"
#import "RCFeedbackDataModel.h"

@interface RCTicketFlyOrderViewController ()<IManagerDelegate,MBProgressHUDDelegate,UIPickerViewDelegate,UIPickerViewDataSource,RCTicketAddUserDelegate,RCTicketFlyTotalPriceDelegate>

@property(nonatomic,retain)RCFlyOrderItemInfo *flyItemDataModel;
@property(nonatomic,retain)NSMutableArray *orderUserArray;
@property(nonatomic,assign)NSInteger cellCount;
@property(nonatomic,copy)  NSString *timeString;
@property(nonatomic,retain)MBProgressHUDEx *progressHub;
@property(nonatomic,retain)RCFlyOrderDetailInfoDataModel *detailDataModel;
@property(nonatomic,assign)int64_t requestID;
@property(nonatomic,assign)int64_t commitRequestID;
@property(nonatomic,retain)UIView *flyToolBar;
@property(nonatomic,retain)UIPickerView *flyPickerView;
@property(nonatomic,assign) BOOL hasRemainTicket;
@property(nonatomic,retain) RCFlyOrderDetailInfoItem *selectItemInfo;
@property(nonatomic,retain) RCFlyOrderDetailInfoItem *currentSelectItemInfo;
@property(nonatomic,retain) UITextField *phoneTextField;

@end

@implementation RCTicketFlyOrderViewController

@synthesize flyItemDataModel = _flyItemDataModel;
@synthesize orderUserArray = _orderUserArray;
@synthesize cellCount = _cellCount;
@synthesize timeString = _timeString;
@synthesize progressHub = _progressHub;
@synthesize detailDataModel = _detailDataModel;
@synthesize requestID = _requestID;
@synthesize commitRequestID = _commitRequestID;
@synthesize hasRemainTicket = _hasRemainTicket;
@synthesize selectItemInfo = _selectItemInfo;
@synthesize currentSelectItemInfo = _currentSelectItemInfo;
@synthesize phoneTextField = _phoneTextField;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithFlyData:(RCFlyOrderItemInfo *)dataModel
{
    self = [super init];
    if (self) {
        self.flyItemDataModel = dataModel;
        
        _orderUserArray = [[NSMutableArray alloc]init];
        [self initKeyBoard];
    }
    return self;
}

-(void)initKeyBoard{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_commitRequestID];
    self.flyPickerView.delegate = nil;
    self.flyPickerView = nil;
    self.flyToolBar = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.flyItemDataModel = nil;
    self.orderUserArray = nil;
    self.timeString = nil;
    self.detailDataModel = nil;
    self.selectItemInfo = nil;
    self.currentSelectItemInfo = nil;
    self.phoneTextField = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"订单填写";
    self.navigationItem.titleView = [self createTitleView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor whiteColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        //        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y,baseVCTableView.frame.size.width,UIScreenHeight-20);
        //        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
    }
    
    UIImageView *headerImageLineView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 4)];
    headerImageLineView.backgroundColor = [UIColor clearColor];
    [headerImageLineView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_ticketOrder_addUser_line.png" ofType:nil]]];
    [self.view addSubview:headerImageLineView];
    [headerImageLineView release];
    
    [self getInfo];
    
}

-(void)updatePickerView{
    
    _flyPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, UIScreenHeight-44-20-150, 320, 150)];
    _flyPickerView.backgroundColor = [UIColor whiteColor];
    _flyPickerView.showsSelectionIndicator = YES;
    
    [self.view addSubview:_flyPickerView];
    _flyPickerView.delegate = self;
    _flyPickerView.hidden = YES;
    
    _flyToolBar = [self createToolBar];
    [self.view addSubview:_flyToolBar];
    _flyToolBar.hidden = YES;
}

- (UIView *) createToolBar
{
    CGFloat yPoint = 0;
    yPoint = _flyPickerView.frame.origin.y-40;
    
    UIView *s = [[[UIView alloc] initWithFrame:CGRectMake(0, yPoint, 320, 40)]autorelease];
    [s setBackgroundColor:kNormalOrangeTextColor];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 50, 40)];
    [leftBtn addTarget:self action:@selector(cancelBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn.titleLabel setFont:[UIFont fontWithName:kFontNameHeiti size:16]];
    [leftBtn setTitleColor:kNormalHeadTextColor forState:UIControlStateNormal];
    [leftBtn setBackgroundColor:[UIColor clearColor]];
    
    [s addSubview:leftBtn];
    [leftBtn release];
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 220, 40)];
    [s addSubview:textLabel];
    [textLabel setBackgroundColor:[UIColor clearColor]];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.text = @"选择舱位";
    [textLabel release];
    
    
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(260, 0, 50, 40)];
    [s addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(confirmBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont fontWithName:kFontNameHeiti size:16]];
    [rightBtn setTitleColor:kNormalHeadTextColor forState:UIControlStateNormal];
    [rightBtn setBackgroundColor:[UIColor clearColor]];
    [rightBtn release];
    return s;
    
}

-(void)getInfo{
    
    _requestID = [[IManager sharedInstance]requestFlyOrderInfo:self.flyItemDataModel.startCityCode withToCity:self.flyItemDataModel.endCityCode withFromDate:self.flyItemDataModel.startDate withAirLine:self.flyItemDataModel.airName withDelegate:self];
    if (_requestID == kInvalidRequestId) {
        
        [RCAppDelegate alertWithCustomizeString:@"加载失败，请稍后重试"];
    }else{
        _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                                   TopHeight:0
                                            withBottomHeight:0
                                               withLeftWidth:0
                                              withRightWidth:0
                                        withExclusiveObjects:nil];
        _progressHub.delegate = self;
        _progressHub.labelText = @"加载中...";
        [self.view addSubview:_progressHub];
        [self.view bringSubviewToFront:_progressHub];
        [_progressHub show:YES];
    }
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        self.detailDataModel = (RCFlyOrderDetailInfoDataModel *)dataModel;
        
        [self updatePickerView];
        [self updateTicketStatus];
        [baseVCTableView reloadData];
        
    }else if(_commitRequestID == requestId){
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        RCFeedbackDataModel *feedbackDataModel = (RCFeedbackDataModel *)dataModel;
        if (feedbackDataModel.errorNO == 0) {
            [RCAppDelegate alertWithCustomizeString:@"提交成功"];
            [self performSelector: @selector(leftButtonClicked) withObject: nil afterDelay: 1.5f];
        }else{
            [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
            
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
    }else if (_commitRequestID == requestId){
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
    }
}

-(void)leftButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark PickView Delegate

-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return [self.detailDataModel.flyItemArray count];
    
}


-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *t = nil;
    
    RCFlyOrderDetailInfoItem *item = [self.detailDataModel.flyItemArray safeObjectAtIndex:row];
    if (item != nil) {
        t = item.flyType;
    }
    return t;
}



- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    RCFlyOrderDetailInfoItem *item = [self.detailDataModel.flyItemArray safeObjectAtIndex:row];
    if (nil == item) {
        return;
    }
    
    self.selectItemInfo = item;
    
}

-(void)updateTicketStatus{
    if (nil == self.detailDataModel) {
        return;
    }
    for (int i = 0; i < [self.detailDataModel.flyItemArray count]; i++) {
        RCFlyOrderDetailInfoItem *item = [self.detailDataModel.flyItemArray safeObjectAtIndex:i];
        if (nil == item) {
            continue;
        }
        if ([self.flyItemDataModel.price floatValue] == item.price) {
            self.currentSelectItemInfo = item;
            self.flyItemDataModel.originPrice = [NSString stringWithFormat:@"%d",(int)item.originPrice];
            self.flyItemDataModel.flyType = item.flyType;
            break;
        }
    }
}

- (void) cancelBtnPressed
{
    _flyPickerView.hidden = YES;
    _flyToolBar.hidden = YES;
}


- (void) confirmBtnPressed
{
    _flyPickerView.hidden = YES;
    _flyToolBar.hidden = YES;
    
    if (nil == self.selectItemInfo || [self.selectItemInfo.flyType isEqualToString:self.currentSelectItemInfo.flyType]) {
        return;
    }
    self.flyItemDataModel.flyType = self.selectItemInfo.flyType;
    self.flyItemDataModel.price = [NSString stringWithFormat:@"%f",self.selectItemInfo.price];
    self.flyItemDataModel.originPrice = [NSString stringWithFormat:@"%f",self.selectItemInfo.originPrice];
    
    self.currentSelectItemInfo = self.selectItemInfo;
    [self getInfo];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    self.cellCount = 6+[_orderUserArray count];
    return self.cellCount;
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSInteger row = [indexPath row];
    
    if (row == 0) {
        cell = [[[RCTicketFlyOrderTimeHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"] autorelease];
        [(RCTicketFlyOrderTimeHeaderCell *)cell bindData:self.flyItemDataModel];
    }else if (row == 1){
        
        cell = [[[RCTicketFlyTimePriceDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"] autorelease];
        [(RCTicketFlyTimePriceDetailCell *)cell bindData:self.flyItemDataModel];
        
        
    }else if (row == 2){
        cell = [[[RCTicketFlySeatTypeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"d"]autorelease];
        [(RCTicketFlyTimePriceDetailCell *)cell bindData:self.flyItemDataModel];
        
    }else if (row == 3){
        
        cell = [[[RCTicketFlyAddUserInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"]autorelease];
        
    }else if (self.cellCount > 6 && row >= 4 && row < self.cellCount-2){
        
        cell = [[[RCTicketUserInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"]autorelease];
        RCTicketOrderUserInfo *userItem = [_orderUserArray safeObjectAtIndex:row-4];
        if (userItem != nil) {
            [(RCTicketUserInfoCell *)cell bindData:userItem];
        }
        
        
    }else if ([indexPath row] == self.cellCount-2){
        cell = [[[RCTicketPhoneInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"]autorelease];
        self.phoneTextField = ((RCTicketPhoneInfoCell *)cell).phoneTextField;
        
    }else if ([indexPath row] == self.cellCount-1){
        
        cell = [[[RCTicketFlyTotalPriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"te"]autorelease];
        [(RCTicketFlyTotalPriceCell *)cell bindData:self.flyItemDataModel];
        ((RCTicketFlyTotalPriceCell *)cell).delegate = self;
    }
    
    return cell;
    
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    if (row == 0) {
        
        return [RCTicketFlyOrderTimeHeaderCell getCellHeight];
        
    }else if (row == 1){
        
        return [RCTicketFlyTimePriceDetailCell getCellHeight];
        
        
    }else if (row == 2){
        
        return [RCTicketFlySeatTypeCell getCellHeight];
        
    }else if (row == 3){
        
        return [RCTicketFlyAddUserInfoCell getCellHeight];
        
    }else if (self.cellCount > 6 && row >= 4 && row < self.cellCount-2){
        
        return [RCTicketUserInfoCell getCellHeight];
        
        
    }else if ([indexPath row] == self.cellCount-2){
        
        return [RCTicketPhoneInfoCell getCellHeight];
        
    }else if ([indexPath row] == self.cellCount-1){
        
        return [RCTicketFlyTotalPriceCell getCellHeight];
        
    }
    
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSInteger row = [indexPath row];
    if (row == 2) {
        _flyPickerView.hidden = NO;
        _flyToolBar.hidden = NO;
        [self.view bringSubviewToFront:_flyPickerView];
        [self.view bringSubviewToFront:_flyToolBar];
        
        RCFlyOrderDetailInfoItem *item = [self.detailDataModel.flyItemArray safeObjectAtIndex:0];
        if (nil == item) {
            return;
        }
        
        self.selectItemInfo = item;
        
    }else if (row == 3){
        RCTicketAddUserViewController *userVC = [[RCTicketAddUserViewController alloc]init];
        userVC.delegate = self;
        UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:userVC];
        [self presentViewController:navi animated:YES completion:nil];
        [userVC release];
        [navi release];
    }
}

-(void)getUserDataModel:(RCTicketOrderUserInfo *)userInfo{
    if (nil == userInfo) {
        return;
    }
    
    [_orderUserArray addObject:userInfo];
    [baseVCTableView reloadData];
}

-(void)commitOrderButtonClick{
    
    if (![[GloableEngineService sharedInstance]alertLoginViewIfUnlogin:self]) {
        return;
    }
    
    if ([_orderUserArray count] == 0) {
        [RCAppDelegate alertWithCustomizeString:@"您还没有添加登机人"];
        return;
    }
    
    if ([NSString stringIsNullOrEmpty:self.phoneTextField.text]) {
        [RCAppDelegate alertWithCustomizeString:@"您还没有留下联系电话"];
        return;
    }
    
    NSString *bduss = [GloableEngineService sharedInstance].bduss;
    
    NSMutableDictionary *postDict = [[[NSMutableDictionary alloc]init]autorelease];
    [postDict setObject:bduss forKey:@"bduss"];
    [postDict setObject:self.flyItemDataModel.airCompany forKey:@"airCompanyName"];
    [postDict setObject:self.flyItemDataModel.airName forKey:@"airline"];
    [postDict setObject:self.flyItemDataModel.airTypeName forKey:@"airplaneType"];
    [postDict setObject:self.flyItemDataModel.startAirport forKey:@"startAirportName"];
    [postDict setObject:self.flyItemDataModel.endAirport forKey:@"endAirportName"];
    NSString *timeString = [NSString stringWithFormat:@"%@ %@",self.flyItemDataModel.startDate,self.flyItemDataModel.startTime];
    [postDict setObject:timeString forKey:@"fromdate"];
    [postDict setObject:self.flyItemDataModel.flyType forKey:@"cabintypename"];
    [postDict setObject:self.flyItemDataModel.price forKey:@"price"];
    [postDict setObject:self.flyItemDataModel.airportFee forKey:@"airportFee"];
    [postDict setObject:self.flyItemDataModel.fuelFee forKey:@"fuelFee"];
    [postDict setObject:self.phoneTextField.text forKey:@"mobile"];
    [postDict setObject:self.flyItemDataModel.startCity forKey:@"fromcity"];
    [postDict setObject:self.flyItemDataModel.endCity forKey:@"tocity"];
    [postDict setObject:@"1" forKey:@"type"];
    
    
    for (int i = 0; i < [_orderUserArray count]; i++) {
        RCTicketOrderUserInfo *user = [_orderUserArray safeObjectAtIndex:i];
        if (nil == user) {
            continue;
        }
        
        [postDict setObject:user.userName forKey:[NSString stringWithFormat:@"name%d",i+1]];
        [postDict setObject:user.userNumType forKey:[NSString stringWithFormat:@"type%d",i+1]];
        [postDict setObject:user.userNum forKey:[NSString stringWithFormat:@"code%d",i+1]];
        
       
    }
    
    
    if (!_progressHub) {
        _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                                   TopHeight:0
                                            withBottomHeight:0
                                               withLeftWidth:0
                                              withRightWidth:0
                                        withExclusiveObjects:nil];
        _progressHub.delegate = self;
        _progressHub.labelText = @"提交中...";
        [self.view addSubview:_progressHub];
    }
    
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
     _commitRequestID = [[IManager sharedInstance]commitFlyOrderInfo:postDict withDelegate:self];
    
}

#pragma mark -
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    
    CGFloat keyboardOriginY = UIScreenHeight-64-keyboardRect.size.height;
    
    CGFloat height = 255+38*[_orderUserArray count]+38;
    
    CGFloat contentOffsetY = height - keyboardOriginY+5;
    
    if (contentOffsetY > 0) {
        [UIView animateWithDuration:0.3f animations:^{
            baseVCTableView.contentOffset = CGPointMake(0, contentOffsetY);
        }];
    }
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3f animations:^{
        baseVCTableView.contentOffset = CGPointMake(0, 0);
    }];
}

@end
